package main

import (
	"fmt"
	"io/fs"
	"os"
	"path/filepath"
	"slices"
	"strings"
)

func main() {
	paths := statAllCodeFiles()
	fmt.Printf("paths: %+v\n", paths)

	if f, err := os.Create("./codes.txt"); nil != err {
		panic(err.Error())
	} else {
		defer f.Close()

		for idx, fp := range paths {
			if idx > 0 {
				fmt.Fprintf(f, "\n\n")
			}
			fmt.Fprintf(f, "===\n%s\n===\n", strings.TrimPrefix(fp, "../../"))
			if bytes, err := os.ReadFile(fp); nil != err {
				panic(err.Error())
			} else {
				if len(bytes) >= 3 {
					if bytes[0] == 0xef && bytes[1] == 0xbb && bytes[2] == 0xbf {
						bytes = bytes[3:]
					}
				}
				if _, err := f.Write(bytes); nil != err {
					panic(err.Error())
				}
			}
		}

	}

}

func statAllCodeFiles() []string {
	excludePrefix := []string{
		"../../vendor/",
		"../../.git/",
		"../../cmd/xiaowu/static/3rd/",
		"../../cmd/code2doc/",
	}
	excludeSuffix := []string{
		".pdf",
		".ico",
		".png",
		".syso",
		".jpg",
		".exe",
	}
	list := []string{}
	walk := func(s string, d fs.DirEntry, err error) error {
		if err != nil {
			return err
		}

		if slices.ContainsFunc(excludePrefix, func(p string) bool {
			return strings.HasPrefix(s, p)
		}) {
			return nil
		}

		if slices.ContainsFunc(excludeSuffix, func(p string) bool {
			return strings.HasSuffix(s, p)
		}) {
			return nil
		}

		if !d.IsDir() {
			list = append(list, s)
		}

		return nil
	}
	filepath.WalkDir("../../", walk)

	return list
}
